package com.nuance.assignment.fileInfo.server.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nuance.assignment.fileInfo.server.service.FileInfoService;
import com.nuance.assignment.fileInfo.shared.FileDTO;
import com.nuance.assignment.fileInfo.shared.PageDTO;
import com.nuance.assignment.fileInfo.shared.ResponseDTO;

/**
 * The controller class to handler File info related requests
 * 
 * @author parag
 *
 */
@Controller("/rest/files")
public class FileInfoController {

	@Autowired
	private FileInfoService fileInfoService;

	/**
	 * Retrieves the children of directory represented by specified path
	 * 
	 * @param path
	 * @param pageDTO
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@ResponseBody
	@RequestMapping
	public ResponseDTO<PageDTO<FileDTO>> getChildren(
			@RequestParam("path") String path, PageDTO<FileDTO> pageDTO)
			throws UnsupportedEncodingException {
		return new ResponseDTO<PageDTO<FileDTO>>(
				StringUtils.hasText(path) ? fileInfoService.getChildren(
						URLDecoder.decode(path, "UTF-8"), pageDTO)
						: fileInfoService.getRoots(pageDTO));
	}

	/**
	 * Retrieves the suggestions to show to user
	 * 
	 * @param path
	 * @param size
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/files/suggestions")
	public ResponseDTO<List<String>> getSuggestions(
			@RequestParam("path") String path,
			@RequestParam(value = "size", defaultValue = "10", required = false) int size) {
		return new ResponseDTO<>(fileInfoService.getSuggestions(path, size));
	}
}
